const {By,Builder,Browser, until} = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome")
const config = require("./config/scrapy.config.json");
const {waitForSeconds} = require("./common");

const startSelenium = (zipcode,keyword,proxies)=>{

    return new Promise((resolve,reject)=>{

        let options = new chrome.Options()
        options.addArguments('--headless');
        options.addArguments('-ingore-certificate-errors')
        options.addArguments('-ingore -ssl-errors')
        options.setAcceptInsecureCerts(true)
        const start = async (zipcode,keyword)=>{
              
             let driver;
             
             try{
         
                 driver =  new Builder().forBrowser(Browser.CHROME)
                                        .setChromeOptions(options)
                                        .build();
         
                 await driver.manage().setTimeouts({implicit:config.loadTimeout});
         
                 await driver.get(`https://www.amazon.com/s?k=${keyword}`);
         
                 await driver.executeScript("document.location.reload()");
         
                 let changeLocTrigger = await driver.findElement(By.css("span#nav-global-location-data-modal-action"));
                 await changeLocTrigger.click();
                 //等2秒
                 await waitForSeconds(2);
         
                 let zipCodeInput = await driver.findElement(By.css("input#GLUXZipUpdateInput.GLUX_Full_Width.a-declarative"));
         
                 await driver.wait(until.elementIsVisible(zipCodeInput),config.waitTimeout)
                 
                 await zipCodeInput.sendKeys(zipcode);
         
                 let applyBtn = await driver.findElement(By.css("input[aria-labelledby='GLUXZipUpdate-announce']"));
                 await applyBtn.click();
         
                 try{
                    //等2秒
                     await waitForSeconds(2);
         
                     let continueBtn =  await driver.findElement(By.css("div.a-popover-footer input#GLUXConfirmClose"))
         
                     await continueBtn.click();     
         
                 }catch(e){
                    //等2秒
                     await waitForSeconds(2);
         
                     let confirmBtn = await driver.findElement(By.css("div.a-popover-footer input#GLUXConfirmClose"));
                     await confirmBtn.click();     
                 }
                //等6秒
                 await waitForSeconds(6);
         
                 const htmlText = await driver.executeScript(`
                     let htmls  = document.getElementsByTagName("html");
                     if(htmls.length > 0){
                        let html = htmls[0];
                       return html.innerHTML
                     }else{
                       return "something wrong"
                   }
                   ;`)
                  
                const html = `<!doctype html><html>${htmlText}</html>`;
                 //           
                var values = await driver.executeScript(`
                    let divs = document.querySelectorAll("div[data-asin]")
                    var values = [];
                    for(var i=0;i<divs.length;i++){
                        /**@type HTMLDivElement*/    
                        let divEle = divs[i];
                        let dataAsin = divEle.getAttribute("data-asin");
                        let selector = "div[data-asin='" + dataAsin + "'] span.a-size-base-plus.a-color-base.a-text-normal";
                        let span = document.querySelector(selector);
                        let title = span && span.innerText;

                        const sellamountSelector = "div[data-asin='" + dataAsin + "'] span.a-size-base";
                        const amountSpans = document.querySelectorAll(sellamountSelector)||[];
                        var amount = "";
                        amountSpans.forEach(function(item,idx){
                            if(item.innerText && item.innerText.includes('bought in past month')){
                                amount = item.innerText;
                            }
                        })

                        values.push({
                            dataAsin:dataAsin||"",
                            title:title||"",
                            amount:amount||""
                        });
                    }
                    return values;  
                `);
                const dataitems = values||[]
                if(htmlText){
                    resolve({html,dataitems})
                }else{
                    reject(new Error("html is not usable"));
                }         
             }catch(e){
                 console.error(e)
             }finally{
                 await driver.quit()
             }
         }

         start(zipcode,keyword);
     }) 
} 

module.exports = {
    startSelenium
};